var util = require('../../utils/util.js');
var utilMd5 = require('../../utils/md5.js');
var app = getApp();
var reload = true;
var page = 1;
var inviteuid = '';
var wxAuthFail = true; 
var SDKVersion = '';


Page({

  /**
   * 页面的初始数据
   */
  data: {
    util: util,
    imgDomain: app.globalData.imgDomain,

    uid: '',
    token: '',
    openid: '',
    canEdit: 0,

    hour: 8,
    brtime:1,
    addressArray: ["全省", "怀集", "佛山", "广州"],
    addressIndex: 0,
    btype:1,

    bottom_nav_data: [],
    isIphone_x: false,
    nav_bgColor: '#ffffff',

    colorSet: '',
    wz_item_img_w_1: 300,

    userphotos:{},
    userInfo: null,
    loginuid: '',
    gametu: [], //广告图
    scheduleShow: false,
    currentObj: '',

    date: '2018-01-01',//默认起始时间  
    date2: '2018-01-24',//默认结束时间 
    startPick:true,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (data) {

    //是否是从分享进来的
    inviteuid = data.inviteuid ? data.inviteuid : '';
    this.getLoginInfo();
    // this.getGametu();

    var tc = app.get_tc();
    var that = this;
    that.setData({
      tc: tc,
      brtime:1,
      btype:2,
    });

    var that = this;


    //获取绑定orgid信息
    app.GetUserInfo(util.orgid, function (res) {
      console.log("绑定机构信息：", res);
      wx.setNavigationBarTitle({
        title: res.uname,
      });
      that.setData({
        org_name: res.uname
      })
    });
    //获取颜色配置
    app.getColorSetData(function (color) {
      that.setData({
        colorSet: color,
      })
      that.resetNavColor();
    });

    //初始化底部导航
    var b_nav_data = app.getBottomNavData('hotel-index/hotel-index', function (data) {
      that.setData({
        bottom_nav_data: data,
        nav_bgColor: data[0].bgcolor,
      });
    });

    wx.getSystemInfo({
      success: function (res) {
        SDKVersion = res.SDKVersion;
        var isIphone_x = (res.model.indexOf('iPhone X') >= 0);
        that.setData({
          tc: app.get_tc(),
          isIphone_x: isIphone_x,
          wz_item_img_w_1: res.windowWidth - 25
        });
      }
    })

    reload = true;

    var currentObj = this.getCurrentObj();
    var currentObjEnd = this.getCurrentObj();
    currentObjEnd.setDate(currentObj.getDate() + 1)
    this.setData({
      currentDateStr: currentObj.getFullYear() + '年' + (currentObj.getMonth() + 1) + '月' + currentObj.getDate() + '日',
      currentDay: -1,
      currentObj: currentObj,
      currentObjStart: currentObj,
      currentObjEnd: currentObjEnd,
      today: currentObj,
      date: currentObj.getFullYear() + "-" + (currentObj.getMonth() + 1) + '-' + currentObj.getDate(),
      dateStart: that.getDateStr(0),
      dateEnd: that.getDateStr(1),
      interval:1,
      time: util.formatNumber(new Date().getHours()) + ':' + util.formatNumber(new Date().getMinutes()),
      hour:(new Date().getHours())
    })
    wx.setStorageSync("dateStartObj", that.data.currentObjStart);
    wx.setStorageSync("dateEndObj", that.data.currentObjEnd);

    this.setSchedule(currentObj);
    
  },

  getLoginInfo: function () {
    var that = this;
    app.LoginUserInfo(function (res) {
      console.log("mine login:", res);
      wxAuthFail = res == -1;//用户拒绝授权
      if (wxAuthFail) {
        return;
      }
      that.setData({
        uid: res.uid,
        openid: res.wxsmall_openid,
        token: res.token
      });

      console.log("mine login111111111:", that.data.uid);
      util.api({
        data: {
          "uid": that.data.uid,
          "publickey": util.publiccode,
          "ac": "userinfo"
        },
        success: function (responseData) {
          console.log("userInfouserInfo:",responseData.data);
          that.setData({
            userInfo: responseData.data
          });
        }
      });
    }, inviteuid);

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var userInfo = wx.getStorageSync('userInfo'); 
    this.setData({
      userInfo: userInfo
    })
    console.log("wx.getStorageSync('userInfo')", userInfo)
    // this.getLoginInfo();
    this.getGametu();
  },
  //获取广告图
  getGametu: function () {
    var that = this;
    console.log("uiduiduiduiduid:", this.data.uid);
    util.api({
      data: {
        "uid": that.data.uid,
        "orgid": util.orgid,
        "publickey": util.publiccode,
        "ac": "getGametu"
      },

      success: function (responseData) {
        console.log("获取广告图", responseData.data);
        that.setData({
          gametu: responseData.data
        })
      }
    });
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },
  //页面分享
  onShareAppMessage: function () {
    var that = this;
    var inviteuid = that.data.loginuid ? that.data.loginuid : '';
    console.log("分享id" + inviteuid);
    if (util.orgid == '15671') {
      return {
        title: that.data.tc == 1 ? '打造全方位的招聘服務' : '打造全方位的招聘服务',
        path: '/pages/index/index?&inviteuid=' + inviteuid
      };
    } else if (util.orgid == '18535') {
      return {
        title: that.data.tc == 1 ? '懷集首家提供公寓、民宿、別墅托管服務平臺' : '怀集首家提供公寓、民宿、别墅托管服务平台',
        path: '/pages/hotel-index/hotel-index?&inviteuid=' + inviteuid
      };
    } else{
      return {
        title: that.data.org_name,
        path: '/pages/index/index?&inviteuid=' + inviteuid
      };
    }
  },


  showEWM: function (e) {
    var shareImgUrl = e.currentTarget.dataset.imgsrc;
    console.log("图片链接：" + shareImgUrl);
    wx.previewImage({
      current: shareImgUrl,
      urls: [shareImgUrl]
    })
  },

  goAtherPage: function (e) {
    var url = e.currentTarget.dataset.link;
    wx.navigateTo({ url: url })
  },
  goAtherPageRedirect: function (e) {
    var url = e.currentTarget.dataset.link;
    wx.redirectTo({ url: url })
  },

  //保存formId
  submitFormId: function (e) {
    app.saveFormId(e.detail.formId);

    var path = e.detail.value.nav_path;
    if (path) {
      wx.redirectTo({ url: path })
    }

  },

  makeCallPhone: function (e) {
    var phoneNum = e.currentTarget.dataset.number;
    console.log("phoneNum:" + phoneNum);
    wx.makePhoneCall({
      phoneNumber: phoneNum,
      success: function (e) {
        console.log("make call success:", JSON.stringify(e));
      },
      fail: function (e) {
        console.log("make call fail:", JSON.stringify(e));
      }
    })
  },
  goMapView: function (e) {
    var addr = e.currentTarget.dataset.addr;
    var lat = parseFloat(addr.lat);
    var lon = parseFloat(addr.lon);
    wx.openLocation({
      latitude: lat,
      longitude: lon,
      scale: 20,
      name: addr.name,
      address: addr.address
    })
  },

  resetNavColor: function () {
    var bg_color = '#d8202d';
    var fg_color = '#ffffff';
    if (this.data.colorSet) {
      var colorJO = this.data.colorSet;
      bg_color = colorJO.titlebg;
      fg_color = colorJO.titlefont;
    }
    wx.setNavigationBarColor({
      frontColor: fg_color,
      backgroundColor: bg_color
    })
  },

  doDay: function (e) {
    var that = this
    var currentObj = that.data.currentObj
    var Y = currentObj.getFullYear();
    var m = currentObj.getMonth() + 1;
    var d = currentObj.getDate();
    var str = ''
    if (e.currentTarget.dataset.key == 'left') {
      m -= 1
      if (m <= 0) {
        str = (Y - 1) + '/' + 12 + '/' + d
      } else {
        str = Y + '/' + m + '/' + d
      }
    } else if (e.currentTarget.dataset.key == 'right') {
      m += 1
      if (m <= 12) {
        str = Y + '/' + m + '/' + d
      } else {
        str = (Y + 1) + '/' + 1 + '/' + d
      }
    }
    currentObj = new Date(str)
    console.log("currentObj：", currentObj)
    this.setData({
      currentDateStr: currentObj.getFullYear() + '年' + (currentObj.getMonth() + 1) + '月' + currentObj.getDate() + '日',
      currentObj: currentObj
    })
    this.setSchedule(currentObj);
  },
  getCurrentObj: function () {
    var objDate = this.data.currentObj
    if (objDate != '') {
      return objDate
    } else {
      var c_obj = new Date()
      var a = c_obj.getFullYear() + '/' + (c_obj.getMonth() + 1) + '/' + c_obj.getDate()
      return new Date(a)
    }
  },
  setSchedule: function (currentObj) {
    var that = this
    var m = currentObj.getMonth() + 1
    var Y = currentObj.getFullYear()
    var d = currentObj.getDate();
    // var dayString = Y + '/' + m + '/' + currentObj.getDate()
    var currentDayNum = new Date(Y, m, 0).getDate();
    console.log("currentDayNum-------------->>>>>>>>>>>>>", currentDayNum);
    currentObj.setDate(1);
    var firstKey = currentObj.getDay();
    var firstKey = firstKey == 0 ? 7 : firstKey;
    var currentDayList = []
    var f = 0
    for (var i = 0; i < 42; i++) {
      let data = []
      if (i < firstKey - 1) {
        currentDayList[i] = ''
      } else {
        if (f < currentDayNum) {
          currentDayList[i] = f + 1
          f = currentDayList[i]
        } else if (f >= currentDayNum) {
          currentDayList[i] = ''
        }
      }
    }
    let dateList = [];
    for (var i = 0; i < 42; i++) {
      let obj = {};
      obj.index = i;
      obj.date = currentDayList[i];
      let btime = [
        { value: "上午09-10點", number: 0, counts: 0 },
        { value: "上午10-11點", number: 0, counts: 0 },
        { value: "下午14-15點", number: 0, counts: 0 },
        { value: "下午15-16點", number: 0, counts: 0 },
        { value: "下午16-17點", number: 0, counts: 0 },
        { value: "晚上18-19點", number: 0, counts: 0 },
        { value: "晚上19-20點", number: 0, counts: 0 },
        { value: "晚上20-21點", number: 0, counts: 0 }];
      obj.btime = btime;
      obj.dateObj = new Date(Y, currentObj.getMonth(), obj.date)
      obj.state = 1;
      dateList.push(obj);
    }
    let btime = [
      { value: "上午09-10點", number: 0, counts: 0 },
      { value: "上午10-11點", number: 0, counts: 0 },
      { value: "下午14-15點", number: 0, counts: 0 },
      { value: "下午15-16點", number: 0, counts: 0 },
      { value: "下午16-17點", number: 0, counts: 0 },
      { value: "晚上18-19點", number: 0, counts: 0 },
      { value: "晚上19-20點", number: 0, counts: 0 },
      { value: "晚上20-21點", number: 0, counts: 0 }];
    that.setData({
      currentDayList: dateList,
      btime: btime
    })
  },

  hideSchedule: function () {
    var that = this;
    if (that.data.startPick) {
      that.hideModal();

    }
  },

  showModal: function () {
    console.log("显示遮罩层")
    var that = this;
    // 显示遮罩层
    var animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })
    this.animation = animation
    animation.translateY(300).step()
    this.setData({
      animationData: animation.export(),
      scheduleShow: true
    })
    setTimeout(function () {
      animation.translateY(0).step()
      this.setData({
        animationData: animation.export(),
        scheduleShow: true
      })
    }.bind(this), 200);
  },

  hideModal: function () {
    // 隐藏遮罩层
    var animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })
    this.animation = animation
    animation.translateY(300).step()
    this.setData({
      animationData: animation.export(),
    })
    setTimeout(function () {
      animation.translateY(0).step()
      this.setData({
        animationData: animation.export(),
        scheduleShow: false
      })
    }.bind(this), 200)
  },

  dateSelected: function (e) {
    var that = this;
    console.log("currentDateObj", this.data.currentObj);
    console.log("e", e.currentTarget.dataset.date);
    var startPick=that.data.startPick;
    if (e.currentTarget.dataset.date != '') {
      this.data.currentObj.setDate(e.currentTarget.dataset.date);
      var currentObj = this.data.currentObj;

      // this.getWaithaoConfig()
      // this.loadDataToList();
      if (this.data.currentObj >= this.data.today) {
        for (var i = 0; i < 42; i++) {
          if (e.currentTarget.dataset.date && e.currentTarget.dataset.date == this.data.currentDayList[i].date) {
            this.setData({
              btime: this.data.currentDayList[i].btime,
              currentDateStr: currentObj.getFullYear() + '年' + (currentObj.getMonth() + 1) + '月' + currentObj.getDate() + '日',
              currentDay: currentObj.getDate(),
              currentObj: currentObj,
              date: that.getYMDString(that.data.currentObj),
            })
            console.log(this.data.currentDayList[i])
          }
        }
        if (startPick) {
          that.setData({
            currentObjStart: currentObj,
            currentObjEnd: currentObj,
            startPick: false
          })
        } else {
          var c_obj = new Date()
          that.setData({
            currentObjEnd: currentObj,
            startPick: true,
            currentDay: -1,
          })
          that.getInterval();
          // 排序
          if (currentObj < that.data.currentObjStart) {
            that.setData({
              currentObjEnd: that.data.currentObjStart,
              currentObjStart: currentObj,
            })

          }
          // 渲染日期
          that.setData({
            dateStart: that.getMDstring(that.data.currentObjStart),
            dateEnd: that.getMDstring(that.data.currentObjEnd),
            currentObj: that.getCurrentObj()
          })
          wx.setStorageSync("dateStartObj", that.data.currentObjStart);
          wx.setStorageSync("dateEndObj", that.data.currentObjEnd);
          that.hideModal()
        }
      } else if (this.data.currentObj != '') {
        that.setData({
          cannotSlide: true
        })
        // wx.showToast({
        //   title: '日期已過',
        // })
      }
    }
    
  },

  //返回日期y-m-d格式
  getYMDString: function (dateObj) {
    var Y = dateObj.getFullYear();
    var M = dateObj.getMonth() + 1 < 10 ? ('' + (dateObj.getMonth() + 1)) : (dateObj.getMonth() + 1) ;
    var D = dateObj.getDate() < 10 ? ('0' + dateObj.getDate()) : dateObj.getDate();
    return (Y+'-'+M+"-"+D)
  },

  // 时间段选择  
  bindDateChange(e) {
    let that = this;
    console.log(e.detail.value)
    that.setData({
      date: e.detail.value,
    })
  },
  bindDateChange2(e) {
    let that = this;
    that.setData({
      date2: e.detail.value,
    })
  },

  //时间选项改变值
  btimePickerChange: function (e) {//选项改变触发事件
    var brtime = e.currentTarget.dataset.brt;
    console.log("选中了:", e);
    this.setData({
      brtime: brtime
    })
  },

  //地址选择
  addressPickerChange: function (e) {//选项改变触发事件
    console.log("选中了:", e);
    this.setData({
      addressIndex: e.detail.value
    })
  },

  //出租时间选项改变值
  btypePickerChange: function (e) {//选项改变触发事件
    var btype = e.currentTarget.dataset.btype;
    console.log("选中了:", e);
    
    // var time = util.formatTime(new Date(),'-',':');
    // 再通过setData更改Page()里面的data，动态更新页面的数据
    var  time = new Date(new Date().setHours(0, 0, 0, 0)).getTime();
    var shidian = time + 10 * 60 * 60 * 1000;
    var shiliudian = time + 16 * 60 * 60 * 1000;
    
    var now = new Date().getTime();
    console.log("time:", time);
    console.log("shidian:", shidian);
    console.log("shiliudian:", shiliudian);
    console.log("now:", now);


    if(btype == 1){ //时租
      if(now >= shidian && now <= shiliudian){

        this.setData({
          btype: btype,
          interval: 4
        })
    }else{
        return false;
      }
    }else if(btype == 2){

      var dd = this.data.currentObjStart;
      var y = dd.getFullYear();
      var m = dd.getMonth() + 1;
      var d = dd.getDate()+1;
      var dateEnd = new Date(y + "/" + m + "/" + d);
      var interval = (dateEnd - this.data.currentObjStart) / (60 * 60 * 24 * 1000)
      wx.setStorageSync("dateEndObj", dateEnd);
      wx.setStorageSync("interval", interval);
      console.log("dateEnd", dateEnd);

      this.setData({
        currentObjEnd: dateEnd,
        btype: btype,
        interval: interval
      })
      // 渲染日期
      var that = this
      this.setData({
        dateStart: that.getMDstring(that.data.currentObjStart),
        dateEnd: that.getMDstring(that.data.currentObjEnd),
      })
    }else if(btype == 3){
      
      
      var dd = this.data.currentObjStart;
      var y = dd.getFullYear();
      var m = dd.getMonth() + 2;
      var d = dd.getDate();
      var dateEnd=new Date(y+"/"+m+"/"+d);
      var interval= (dateEnd - this.data.currentObjStart) / (60 * 60 * 24 * 1000)
      wx.setStorageSync("dateEndObj", dateEnd);
      wx.setStorageSync("interval", interval);
      console.log("dateEnd",dateEnd);
      
      this.setData({
        currentObjEnd: dateEnd,
        btype: btype,
        interval: interval
      })
      // 渲染日期
      var that=this
      this.setData({
        dateStart: that.getMDstring(that.data.currentObjStart),
        dateEnd: that.getMDstring(that.data.currentObjEnd),
      })

    }


    

    
  },




  selectAddress: function () {
    var that = this;
    wx.chooseLocation({
      success: function (res) {
        console.log("选择地址：", res);
        var userInfo = that.data.userInfo;
        userInfo.addresschoose = res.address;
        userInfo.lon = res.longitude;
        userInfo.lat = res.latitude;

        that.setData({
          userInfo: userInfo
        })
        wx.setStorageSync("userInfo", userInfo);
        that.updateLocation()
      },
    })
  },
  updateLocation:function(){
    var that = this;
    var tmpmd5 = utilMd5.hexMD5(app.globalData.userInfo.uid + "usercominfo" + app.globalData.userInfo.token);
    var params = {
      "privatekey": tmpmd5,
      "ac": "usercominfo",
      "edituid": app.globalData.userInfo.uid,
      "uid": that.data.userInfo.uid,
      "realname": that.data.userInfo.uname,
      "phone": that.data.userInfo.phone,
      "addresschoose": that.data.userInfo.addresschoose,
      "lon": that.data.userInfo.lon,
      "lat": that.data.userInfo.lat,
    };
    console.log("编辑资料params：", params);
    util.api({
      data: params,
      method: "POST",
      success: function (responseData) {
        console.log(responseData);
        if (responseData.data.res) {
          app.dialogToast("成功获取定位", "success", function () {
          });
        } else {
          wx.showToast({
            title: responseData.data.msg,
          })
        }
      }
    });
  },
  // 获取AddDayCount天后的日期
  getDateStr: function (AddDayCount) {
    var dd = new Date();
    dd.setDate(dd.getDate() + AddDayCount);//获取AddDayCount天后的日期 
    var y = dd.getFullYear();
    var m = dd.getMonth() + 1;//获取当前月份的日期 
    var d = dd.getDate();
    // return y + "-" + util.formatNumber(m) + "-" + util.formatNumber(d);
    return util.formatNumber(m) + "月" + util.formatNumber(d) + "日";
  },

  getInterval: function () {
    var days = this.data.currentObjEnd.getTime() - this.data.currentObjStart.getTime();
    var day = Math.abs(parseInt(days / (1000 * 60 * 60 * 24)));
    this.setData({
      interval: day
    })
  },
  getMDstring: function (currentObj){
    return util.formatNumber(currentObj.getMonth() + 1) + "月" + util.formatNumber(currentObj.getDate()) + "日"
  }
})